//
//  MHSettingCircleJoinTypeViewController.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/4/20.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHSettingCircleJoinTypeViewController.h"
#import "MHSetPriceItemCell.h"
#import "MHSettingPriceViewModel.h"
#import "MHSettingCircleJoinTypeViewModel.h"
#import "MHDiscountTableViewView.h"
#import "MHCommonItemViewModel.h"
#import "MHAlertTableViewModel.h"
#import "MHPriceRange.h"
@interface MHSettingCircleJoinTypeViewController ()

@property(nonatomic, strong) MHSettingCircleJoinTypeViewModel *viewModel;
@property(nonatomic, assign) int  rowIndex;

@property(nonatomic, strong)  MHSetPriceItemCell *priceItemCell;
@property(nonatomic, strong) MHPriceRange *range;
@property(nonatomic, assign) double tempPrice;
@end

@implementation MHSettingCircleJoinTypeViewController
@dynamic viewModel;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1)
    {
        MHSetPriceItemCell *cell = [MHSetPriceItemCell cellWithTableView:tableView];
        __weak __typeof(self)weakSelf = self;
        cell.priceTextFeild.text = [NSString stringWithFormat:@"%@",[@(self.viewModel.circleInfo.joinPrice ?: 0) stringValue]];
        self.tempPrice = self.viewModel.circleInfo.joinPrice;
        self.priceItemCell = cell;
        if (self.viewModel.circleInfo.isOpenActivity) {
            cell.priceTextFeild.userInteractionEnabled = false;
        }
        cell.priceTextFeild.bk_shouldEndEditingBlock = ^BOOL(UITextField *textFeild) {
            weakSelf.viewModel.circleInfo.joinPrice = [cell.priceTextFeild.text doubleValue];
            
            if (self.tempPrice != [cell.priceTextFeild.text doubleValue]) {
                weakSelf.viewModel.circleInfo.goOnPrice = [cell.priceTextFeild.text doubleValue];
                MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[self.viewModel.dataSource.count -1];
                MHCommonItemViewModel *object = groupViewModel.itemViewModels.firstObject;
                object.subtitle = @"无折扣";
                object.title = [NSString stringWithFormat:@"续费价格（￥%.1f年）",(CGFloat)weakSelf.viewModel.circleInfo.goOnPrice];
                [self.tableView reloadSection:self.viewModel.dataSource.count -1 withRowAnimation:UITableViewRowAnimationNone];
            }
           
//            [weakSelf.zh_popupController dismiss];
            
            return YES;
        };
        YYCache *cache=[YYCache cacheWithName:MHCacheGlobleKey];
        MHPriceRange *range = [cache objectForKey:MHCirclePriceRange];
        if (!range) {
            range = [MHPriceRange new];
            range.minPrice = 10;
            range.maxPrice = 10000;
        }
        self.range = range;
        NSAttributedString *str1 = [[NSAttributedString alloc]initWithString:@"可设置" attributes:@{NSForegroundColorAttributeName:[UIColor colorFromHexString:@"#8e8e8e"],NSFontAttributeName:[UIFont systemFontOfSize:14]}];
        
        NSAttributedString *str2= [[NSAttributedString alloc]initWithString:[NSString stringWithFormat:@"%.0f~%.0f",(CGFloat)range.minPrice,(CGFloat)range.maxPrice] attributes:@{NSForegroundColorAttributeName:[UIColor colorFromHexString:@"#FE7567"],NSFontAttributeName:[UIFont systemFontOfSize:14]}];
        NSAttributedString *str3 = [[NSAttributedString alloc]initWithString:@"元" attributes:@{NSForegroundColorAttributeName:[UIColor colorFromHexString:@"#8e8e8e"],NSFontAttributeName:[UIFont systemFontOfSize:14]}];
        
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@""];
        [string appendAttributedString:str1];
        [string appendAttributedString:str2];
        [string appendAttributedString:str3];
        cell.tipsLable.attributedText = string;
        
        
        return cell;
    }else
    {
        return [MHCommonCell cellWithTableView:tableView];
    }
    
}

-(void)configureCell:(MHCommonCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    if (indexPath.section == (self.viewModel.dataSource.count -1) && self.viewModel.circleInfo.payType == MHCirclPayTypeCharge ) {
        MHCommonItemViewModel *model =  (MHCommonItemViewModel *)object;
         __weak __typeof(self)weakSelf = self;
        model.operation = ^{
            weakSelf.zh_popupController = [zhPopupController new];
            NSMutableArray *discountArray = [NSMutableArray arrayWithCapacity:50];
            for (CGFloat price = 9.9; price >= 5.0; price = price - 0.1) {
                MHAlertTableViewModel *discount1 = [MHAlertTableViewModel new];
                discount1.titile = [NSString stringWithFormat:@"%.1f折",price];
                discount1.price = price;
                discount1.operationBlock = ^{
                    
                    //[self.viewModel.cancelBlackMemberCommand execute:@(circleMember.userId)];
//                    [weakSelf.zh_popupController dismiss];
                };
                [discountArray addObject:discount1];
            }
            
            
            MHAlertTableViewModel *discount3 = [MHAlertTableViewModel new];
            discount3.titile = @"无折扣";
            discount3.price = 10;
            discount3.operationBlock = ^{
//                [weakSelf.viewModel.removeMemberCommand execute:@(circleMember.userId)];
                
//                [weakSelf.zh_popupController dismiss];
            };
            
        
            
            [discountArray addObject:discount3];
            MHDiscountTableViewView *discout = [[MHDiscountTableViewView alloc] initWithDataSource:discountArray];
            discout.footerView = [MHDiscountTableViewFooter mh_viewFromXib];
            [discout.footerView.cancelBtn bk_whenTapped:^{
                
                [weakSelf.zh_popupController dismiss];
            }];
            [discout.footerView.comfirmBtn bk_whenTapped:^{
                weakSelf.viewModel.circleInfo.goOnPrice = discout.currentDisCount * 0.1 *  weakSelf.viewModel.circleInfo.joinPrice;
                
                MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[self.viewModel.dataSource.count -1];
                MHCommonItemViewModel *object = groupViewModel.itemViewModels.firstObject;
                
                
                object.subtitle = discout.currentDisCount == 10 ? @"无折扣": [NSString stringWithFormat:@"%.1f折",discout.currentDisCount];
                object.title = [NSString stringWithFormat:@"续费价格（￥%.1f年）",(CGFloat)weakSelf.viewModel.circleInfo.goOnPrice];
                [self.tableView reloadSection:self.viewModel.dataSource.count -1 withRowAnimation:UITableViewRowAnimationNone];
                [weakSelf.zh_popupController dismiss];
            }];
            
            discout.width = self.view.width * 0.8;
            discout.height = 300;
            [weakSelf.zh_popupController presentContentView:discout];
        };
    }
    [cell bindViewModel:object];
}

//MHCommonGroupViewModel *groupViewModel = self.viewModel.dataSource[indexPath.section];
//    MHCommonItemViewModel *object = groupViewModel.itemViewModels[indexPath.row];

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.viewModel.didSelectCommand execute:indexPath];
//    self.rowIndex  = indexPath.row;
    [self.tableView reloadData];
}


-(void)bindViewModel
{
    [super bindViewModel];
}

-(void)rightButtonClick
{
    if ([self.viewModel.circleInfo currentUserIsOwner]) {
        [self.priceItemCell.priceTextFeild resignFirstResponder];
        
        if (self.viewModel.circleInfo.joinPrice <self.range.minPrice || self.viewModel.circleInfo.joinPrice > self.range.maxPrice ) {
            [MBProgressHUD mh_showTips:@"输入范围有误"];
            return;
        }
        
         self.viewModel.circleInfo.joinPrice = [self.priceItemCell.priceTextFeild.text doubleValue];
        [[self.viewModel.updateInfoCommand execute:nil] subscribeNext:^(id x) {
            
            [MBProgressHUD  mh_showTips:@"保存成功"];
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
